﻿/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Windows.Forms;

namespace TeachMe.Application.ComboItems
{
    public class ComboBoxItem<T>
    {
        public ComboBoxItem(T item, string caption)
        {
            Item = item;
            Caption = caption;
        }

        public ComboBoxItem(T item)
        {
            Item = item;
        }

        public T Item { get; set; }
        public string Caption { get; set; }

        public override string ToString()
        {
            return Caption ?? Item.ToString();
        }

        public static void Select(ComboBox combo, T value)
        {
            foreach (ComboBoxItem<T> item in combo.Items)
            {
                if (item.Item.Equals(value))
                {
                    combo.SelectedItem = item;
                    return;
                }
            }

            throw new InvalidOperationException();
        }

        public static void Select(ComboBox combo, T value, Func<T, T, bool> comparer)
        {
            foreach (ComboBoxItem<T> item in combo.Items)
            {
                if (comparer(item.Item, value))
                {
                    combo.SelectedItem = item;
                    return;
                }
            }

            throw new InvalidOperationException();
        }

        public static T GetSelection(ComboBox combo)
        {
            return ((ComboBoxItem<T>)combo.SelectedItem).Item;
        }

        public static T GetSelection(ToolStripComboBox combo)
        {
            return ((ComboBoxItem<T>)combo.SelectedItem).Item;
        }
    }
}
